<template>
  <!-- 顶部操作栏 -->
  <div class="operation-bar">
    <div class="left-operations">
      <el-select
          v-model="selectValue"
          placeholder="请选择查询条件"
          style="width: 200px"
          @change="changeQueryCondition"
          class="query-select"
      >
        <el-option
            v-for="item in selectCondition"
            :key="item.prop"
            :label="item.name"
            :value="item.prop"
        />
      </el-select>

      <el-input
          v-model="queryCondition.inputCondition"
          style="width: 220px"
          placeholder="请输入查询内容"
          class="query-input"
      />

      <el-button
          type="primary"
          size="large"
          @click="query()"
          class="query-btn"
      >
        <i class="el-icon-search"></i>查询
      </el-button>
    </div>

    <div class="right-operations">
      <el-button
          type="success"
          @click="addSupplierDialogVisible = true"
          class="action-btn"
      >
        <i class="el-icon-plus"></i>新增供应商
      </el-button>
      <el-button
          plain
          @click="resetConditionAndQuery"
          class="action-btn"
      >
        <i class="el-icon-refresh"></i>重置
      </el-button>
    </div>
  </div>

  <!-- 供应商表格 -->
  <div class="table-container">
    <el-card shadow="hover" class="table-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">
            <i class="el-icon-tickets"></i> 供应商列表
          </span>
          <span class="card-total">共 {{ pageInfo.total }} 条记录</span>
        </div>
      </template>

      <el-table
          :data="pageInfo.list"
          style="width: 100%"
          stripe
          v-loading="loading"
          class="data-table"
      >
        <el-table-column prop="id" label="序号" width="100" align="center" />
        <el-table-column prop="supplierName" label="供应商名称" width="180" show-overflow-tooltip />
        <el-table-column prop="contacts" label="联系人" width="120" align="center" />
        <el-table-column prop="contactPhone" label="联系电话" width="140" align="center" />
        <el-table-column prop="contactAddress" label="联系地址" min-width="200" show-overflow-tooltip />
        <el-table-column prop="accountNo" label="开户账号" width="180" show-overflow-tooltip />
        <el-table-column label="操作" width="280" fixed="right" align="center">
          <template #default="scope">
            <el-button
                type="primary"
                size="small"
                @click="openProductList(scope.row)"
                class="table-btn"
            >
              <i class="el-icon-goods"></i>选择商品
            </el-button>
            <el-button
                type="warning"
                size="small"
                @click="openUpdateDialog(scope.row)"
                class="table-btn"
            >
              <i class="el-icon-edit"></i>修改
            </el-button>
            <el-button
                type="danger"
                size="small"
                @click="confirmDel(scope.row.id)"
                class="table-btn"
            >
              <i class="el-icon-delete"></i>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="pageInfo.pageNum"
            v-model:page-size="pageInfo.pageSize"
            :page-sizes="[3, 5, 7, 10]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageInfo.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            class="custom-pagination"
        />
      </div>
    </el-card>
  </div>

  <!-- 新增供应商对话框 -->
  <el-dialog
      v-model="addSupplierDialogVisible"
      @open="addSupplierFormRef.value?.clearValidate()"
      @close="addSupplierFormRef.value?.resetFields()"
      title="新增供应商"
      width="600px"
      class="custom-dialog"
  >
    <div class="dialog-header">
      <i class="el-icon-user-solid"></i>
      <span>填写供应商信息</span>
    </div>

    <el-form
        :model="addSupplierForm"
        :rules="rules"
        ref="addSupplierFormRef"
        label-width="100px"
        class="dialog-form"
    >
      <div class="form-row">
        <el-form-item label="供应商名称" prop="supplierName">
          <el-input v-model="addSupplierForm.supplierName" placeholder="请输入供应商名称" />
        </el-form-item>
        <el-form-item label="联系人" prop="contacts">
          <el-input v-model="addSupplierForm.contacts" placeholder="请输入联系人" />
        </el-form-item>
      </div>

      <div class="form-row">
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="addSupplierForm.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="联系邮箱" prop="contactEmail">
          <el-input v-model="addSupplierForm.contactEmail" placeholder="请输入联系邮箱" />
        </el-form-item>
      </div>

      <el-form-item label="联系地址" prop="contactAddress">
        <el-input
            v-model="addSupplierForm.contactAddress"
            placeholder="请输入联系地址"
            type="textarea"
            :rows="2"
        />
      </el-form-item>

      <div class="form-row">
        <el-form-item label="开户银行" prop="bankOfDeposit">
          <el-input v-model="addSupplierForm.bankOfDeposit" placeholder="请输入开户银行" />
        </el-form-item>
        <el-form-item label="开户帐号" prop="accountNo">
          <el-input v-model="addSupplierForm.accountNo" placeholder="请输入开户帐号" />
        </el-form-item>
      </div>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addSupplierDialogVisible = false" class="cancel-btn">取消</el-button>
        <el-button type="primary" @click="submitAddForm" class="confirm-btn">提交</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 修改供应商对话框 -->
  <el-dialog
      v-model="updateSupplierDialogVisible"
      title="修改供应商"
      @close="updateSupplierFormRef.value?.resetFields()"
      width="600px"
      class="custom-dialog"
  >
    <div class="dialog-header">
      <i class="el-icon-edit"></i>
      <span>修改供应商信息</span>
    </div>

    <el-form
        :model="updateSupplierForm"
        :rules="rules"
        ref="updateSupplierFormRef"
        label-width="100px"
        class="dialog-form"
    >
      <div class="form-row">
        <el-form-item label="供应商名称" prop="supplierName">
          <el-input v-model="updateSupplierForm.supplierName" />
        </el-form-item>
        <el-form-item label="联系人" prop="contacts">
          <el-input v-model="updateSupplierForm.contacts" />
        </el-form-item>
      </div>

      <div class="form-row">
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="updateSupplierForm.contactPhone" />
        </el-form-item>
        <el-form-item label="联系邮箱" prop="contactEmail">
          <el-input v-model="updateSupplierForm.contactEmail" />
        </el-form-item>
      </div>

      <el-form-item label="联系地址" prop="contactAddress">
        <el-input v-model="updateSupplierForm.contactAddress" type="textarea" :rows="2" />
      </el-form-item>

      <div class="form-row">
        <el-form-item label="开户银行" prop="bankOfDeposit">
          <el-input v-model="updateSupplierForm.bankOfDeposit" />
        </el-form-item>
        <el-form-item label="开户帐号" prop="accountNo">
          <el-input v-model="updateSupplierForm.accountNo" />
        </el-form-item>
      </div>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="updateSupplierDialogVisible = false" class="cancel-btn">取消</el-button>
        <el-button type="primary" @click="submitUpdateForm" class="confirm-btn">修改</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 选择商品列表对话框 -->
  <el-dialog
      v-model="openProductSelectDialog"
      title="选择商品"
      width="1300px"
      :close-on-click-modal="false"
      @close="closeQueryPro"
      class="product-dialog"
  >
    <div class="dialog-header">
      <i class="el-icon-s-goods"></i>
      <span>选择供应商品</span>
    </div>

    <el-card shadow="never" class="search-card">
      <el-form
          :inline="true"
          :model="queryProductForm"
          ref="queryPrdFormRef"
          class="search-form"
      >
        <div class="search-row">
          <el-form-item label="商品名称" class="search-form-item">
            <el-input
                v-model="queryProductForm.pname"
                clearable
                placeholder="请输入商品名称"
                style="width: 150px;"
            />
          </el-form-item>
          <el-form-item label="商品型号" class="search-form-item">
            <el-input
                v-model="queryProductForm.pmodel"
                clearable
                placeholder="请输入商品型号"
                style="width: 150px;"
            />
          </el-form-item>
          <el-form-item label="查询条件" class="search-form-item">
            <el-select
                v-model="queryProductForm.queryconditon"
                placeholder="请选择查询条件"
                clearable
                style="width: 180px;"
            >
              <el-option label="商品类型" value="byType" />
              <el-option label="商品采购价" value="byPrice" />
              <el-option label="最低库存" value="byStore" />
            </el-select>
          </el-form-item>
          <el-form-item label="查询值" class="search-form-item">
            <el-input
                v-model="queryProductForm.inputVal"
                placeholder="请输入查询值"
                style="width: 150px;"
                clearable
            />
          </el-form-item>
        </div>

        <div class="search-row">
          <el-form-item label="商品颜色" class="search-form-item">
            <el-select
                v-model="queryProductForm.pcolor"
                placeholder="全部颜色"
                clearable
                style="width: 150px;"
            >
              <el-option label="黑色" :value="0" />
              <el-option label="白色" :value="1" />
              <el-option label="粉色" :value="3" />
              <el-option label="红色" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="商品品牌" class="search-form-item">
            <el-select
                v-model="queryProductForm.pbrand"
                placeholder="全部品牌"
                clearable
                style="width: 150px;"
                @click="queryAllBrank"
            >
              <!-- 动态渲染品牌选项 -->
              <el-option
                  v-for="brand in brandList"
                  :key="brand.brandName"
                  :label="brand.brandName"
                  :value="brand.brandName"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="商品分类" class="search-form-item">
            <el-select
                v-model="queryProductForm.ptype"
                placeholder="全部分类"
                clearable
                style="width: 150px;"
                @click="queryAllType"
            >
              <el-option
                  v-for="type in typeList"
                  :key="type.id"
                  :label="type.typeName"
                  :value="type.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item class="search-form-item">
            <el-button
                type="primary"
                @click="queryProductByCondition"
                class="search-btn"
                style="margin-left: 10px;"
            >
              <i class="el-icon-search"></i>搜索
            </el-button>
          </el-form-item>
        </div>
      </el-form>
    </el-card>

    <el-card shadow="never" class="product-table-card">
      <template #header>
        <div class="table-header">
          <span class="table-title">商品列表</span>
          <span class="table-tips">提示：已添加的商品将禁用选择</span>
        </div>
      </template>

      <el-table
          :data="goodsList"
          border
          style="width: 100%;"
          @selection-change="handleSelectionChange"
          stripe
          class="product-table"
          v-loading="productLoading"
      >
        <el-table-column label="序号" prop="id" width="70" align="center" />
        <el-table-column type="selection" :selectable="isSelectable" width="60" align="center" />
        <el-table-column label="商品名称" prop="gname" min-width="180" show-overflow-tooltip />
        <el-table-column label="商品类型" prop="typeName" min-width="120" align="center" />
        <el-table-column label="商品采购价" prop="purchasePrice" min-width="120" align="center">
          <template #default="scope">
            <span class="price-text">¥{{ scope.row.purchasePrice }}</span>
          </template>
        </el-table-column>
        <el-table-column label="商品品牌" prop="gbrand" min-width="120" align="center" />
        <el-table-column label="商品型号" prop="gmodel" min-width="150" show-overflow-tooltip />
        <el-table-column label="最低库存" prop="minStock" min-width="100" align="center" />
        <el-table-column label="商品颜色" prop="gcolor" min-width="100" align="center">
          <template #default="scope">
            <el-tag
                :type="getColorType(scope.row.gcolor)"
                size="small"
                class="color-tag"
            >
              <span v-if="scope.row.gcolor == 0">黑色</span>
              <span v-else-if="scope.row.gcolor == 1">白色</span>
              <span v-else-if="scope.row.gcolor ==2">红色</span>
              <span v-else-if="scope.row.gcolor == 3">粉色</span>
              <span v-else>未知</span>
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <div class="pagination-container">
      <el-pagination
          v-model:current-page="chooseProdpageInfo.pageNum"
          v-model:page-size="chooseProdpageInfo.pageSize"
          :page-sizes="[6, 9, 12, 15]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="chooseProdpageInfo.total"
          @size-change="handleChooseSizeChange"
          @current-change="handleChooseCurrentChange"
          class="custom-pagination"
      />
    </div>

    <!-- 底部按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <div class="selection-info">
          已选择 <span class="selection-count">{{ selectedIds.length }}</span> 个商品
        </div>
        <div class="footer-buttons">
          <el-button @click="openProductSelectDialog=false" class="cancel-btn">关闭</el-button>
          <el-button type="primary" @click="addProsForSupplier" class="confirm-btn">保存选择</el-button>
        </div>
      </span>
    </template>
  </el-dialog>

  <!-- 已选商品对话框 -->
  <el-dialog
      v-model="querySupplierDialogVisible"
      title="供应商商品管理"
      width="1000px"
      class="custom-dialog supplier-products-dialog"
  >
    <div class="dialog-header">
      <i class="el-icon-s-shop"></i>
      <span>供应商商品列表 - {{ supplierName }}</span>
    </div>

    <div class="supplier-info">
      <el-button type="primary" @click="showProdList" class="action-btn">
        <i class="el-icon-plus"></i>选择商品
      </el-button>
      <span class="product-count">已选择 {{ selectedProducts.length }} 个商品</span>
    </div>

    <el-card shadow="never" class="selected-products-card">
      <el-table
          :data="selectedProducts"
          border
          style="width: 100%;"
          stripe
          empty-text="暂无商品，请点击上方按钮添加"
          class="selected-table"
      >
        <el-table-column prop="id" label="商品ID" width="90" align="center" />
        <el-table-column prop="gname" label="商品名称" min-width="200" show-overflow-tooltip />
        <el-table-column prop="purchasePrice" label="采购价" width="120" align="center">
          <template #default="scope">
            <span class="price-text">¥{{ scope.row.purchasePrice }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="marketPrice" label="市场价" width="120" align="center">
          <template #default="scope">
            <span class="price-text">¥{{ scope.row.marketPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center" fixed="right">
          <template #default="scope">
            <el-button
                type="danger"
                size="small"
                @click="removeProduct(scope.row)"
                class="delete-btn"
            >
              <i class="el-icon-delete"></i>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="querySupplierDialogVisible = false" class="cancel-btn">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>


<script setup>

// 原有的 script 内容完全保持不变
import {onMounted, reactive, ref} from "vue";
import api from '@/utils/request.js';
import {ElMessage, ElMessageBox} from "element-plus";
import qs from "qs";

// 添加一个简单的加载状态
const loading = ref(false);
const productLoading = ref(false);

// 添加颜色标签类型方法
const getColorType = (color) => {
  const types = ['', 'success', 'danger', 'warning'];
  return types[color] || 'info';
};

// 原有的所有方法、响应式数据等都保持不变
// ... 原有的所有代码


// 判断商品是否可选中（已存在的商品禁用）
const isSelectable = (row) => {
  // 检查当前商品 ID 是否在供应商已有的商品列表中
  const isAlreadyAdded = selectedProducts.value.some(item => item.id === row.id);
  // 已存在则返回 false（禁用），否则返回 true（可选中）
  return !isAlreadyAdded;
};
/*新增供应商品*/
//为供应商添加商品信息
//定义一个全局的变量用来记录选择的供应商的id方便后续的插入
let supplierId = ref(0)
// 存储选中行的 id 集合
const selectedIds = ref([]);
// 选中行变化时触发
const handleSelectionChange = (selectedRows) => {
  // selectedRows 是当前所有选中的行数据数组
  // 提取每行的 id，组成新数组
  selectedIds.value = selectedRows.map(row => row.id);

  // 调试：打印选中的 id 集合（可选）
  console.log("选中的商品 id 集合：", selectedIds.value);
};
//拼接参数
// 生成后端需要的参数格式：{ggSupplierGoods: [{sid: x, gid: y}, ...]}
const buildProductList = () => {
  // 1. 遍历选中的 pid，将属性名从 pid 改为 gid（与后端实体类一致）
  const goodsList = selectedIds.value.map(pid => ({
    sid: supplierId.value,  // 供应商ID
    gid: pid                // 商品ID（后端用 gid，而非 pid）
  }));

  // 2. 包装到 ggSupplierGoods 字段中（与后端 DTO 字段名一致）
  return { ggSupplierGoods: goodsList };
};

// 保存供应商品
const addProsForSupplier = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning("请先选择至少一个商品保存");
    return;
  }

  const requestData = buildProductList();
  console.log("发送的参数：", requestData); // 确认格式正确

  api.postJson("supplier/addPros", requestData).then(result => {
    if (result.code === 200) {
      ElMessage.success("保存成功");
      selectedIds.value = [];
      openProductSelectDialog.value = false;
      queryProduct(supplierId.value);
    } else {
      ElMessage.error("保存失败,联系管理员");
    }
  });
};

/*选择供应商品*/
const queryPrdFormRef=ref()

//点击关闭后
const closeQueryPro=()=>{
//重置查询表单
  queryProductForm.value={
    pname: "",
    pmodel: "",
    queryconditon:"",
    inputVal: "",
    pcolor: "",
    pbrand: "",
    ptype: "",
  }
  chooseProdpageInfo.value.pageNum=1
  chooseProdpageInfo.value.pageSize=6

  openProductSelectDialog.value = false

}
let typeList = ref([])

//查询所有的分类
const queryAllType =()=>{
  api.get("GgType/listAllType1").then(result=>{
    typeList.value = result.data.filter(type => type.id != 10);
    console.log(queryProductForm.value.ptype)
  })
}
//查询所有的品牌
const brandList = ref([])
const queryAllBrank=()=>{
  api.get("GgBrand/listAllBrand1").then(result=>{
    brandList.value=result.data
    //console.log(queryProductForm.value.pbrand)
  })
}

//点击搜索之后
const queryProductByCondition=()=>{
  chooseProdpageInfo.value.pageNum=1
  showProdList()
  //log(queryProductForm.value)
  console.log(supplierId.value)
}
//查询
const queryProductForm = ref({
  pname: "",
  pmodel: "",
  queryconditon:"",
  inputVal: "",
  pcolor: "",
  pbrand: "",
  ptype: "",
})
//分页
const chooseProdpageInfo = ref({
  pageNum: 1,
  pageSize: 6,
  total: 0
})
//封装商品信息对象
let goodsList = ref([])

//改变每页显示的记录数
const handleChooseSizeChange=(pageSize)=>{
  chooseProdpageInfo.value.pageSize = pageSize
  chooseProdpageInfo.value.pageNum = 1
  //重新查询
  showProdList()
}
//改变页码
const handleChooseCurrentChange=(pageNum)=>{
  chooseProdpageInfo.value.pageNum = pageNum
  //重新查询
  showProdList()
}



const showProdList=()=>{
  //打开对话框
  openProductSelectDialog.value = true

  //合并查询条件/分页以及查询条件
  const searchParams = {
    // 展开查询条件对象（pname、pmodel、pcolor 等）
    ...queryProductForm.value,
    // 展开分页信息对象（pageNum、pageSize、total）
    ...chooseProdpageInfo.value
  };
  //向后端接口发送请求
  api.get("GcGoods/listAll",searchParams).then(result=>{
    goodsList.value=result.data.list
    chooseProdpageInfo.value.total=result.data.total
  })
}


//打开商品列表的对话框
const querySupplierDialogVisible=ref(false)

//打开选择新增商品的对话框
const openProductSelectDialog = ref(false);

//封装接收接口的对象
const selectedProducts = ref([])

const supplierName=ref("")

const openProductList=(row)=>{
  supplierName.value=row.supplierName
  querySupplierDialogVisible.value=true
  queryProduct(row.id)
  //为全局的供应商id赋值
  supplierId.value=row.id
}

const queryProduct=(sid)=>{
  api.get("/supplier/product/list", {supplierId:sid}).then(result=>{
    if (result.code==200){
      selectedProducts.value=result.data
    }
  })
}

/*删除供应商品*/
/*删除供应商品 - 带确认提示*/
const removeProduct = (product) => {
  // 1. 弹出确认框
  ElMessageBox.confirm(
      '此操作将移除该供应商的此商品，是否继续？',
      '删除确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
  )
      .then(() => {
        // 2. 用户点击确认后，执行删除请求
        api.post("/supplier/product/del", {
          gid: product.id,
          sid: product.sid
        }).then(result => {
          if (result.code === 200) {
            ElMessage.success("删除成功");
            // 3. 刷新商品列表
            queryProduct(product.sid);
          } else {
            ElMessage.error("删除失败,联系管理员");
          }
        });
      })
      .catch(() => {
        // 4. 用户点击取消，提示操作取消
        ElMessage.info("已取消删除");
      });
};



/*重置*/
const resetConditionAndQuery=()=>{
  queryCondition.value.pageNum=1
  queryCondition.value.pageSize=3
  selectValue.value=""
  queryCondition.value.inputCondition=""
  query()
  selectedRows.value = []; // 清空选中行

}

/*删除*/
const confirmDel = (id) => {
  // 1. 先弹确认框，提示用户是否删除
  ElMessageBox.confirm(
      '此操作将永久删除该供应商，是否继续？', // 确认框内容
      '提示', // 确认框标题
      {
        confirmButtonText: '确认', // 确认按钮文字
        cancelButtonText: '取消', // 取消按钮文字
        type: 'warning' // 确认框类型（warning/info/error/success）
      }
  )
      .then(() => {
        // 2. 用户点击“确认”后，携带 id 发送删除请求
        api.post("supplier/del", { ids: id }).then(res => {
          if (res.code == 200) {
            ElMessage.success("删除成功");
            queryCondition.value.pageNum=1
            query(); // 重新查询列表，刷新数据
          } else {
            ElMessage.error("删除失败，联系管理员");
          }
        });
      })
      .catch(() => {
        // 3. 用户点击“取消”后，提示取消操作（可选）
        ElMessage.info("已取消删除");
      });
};


/*/!*批量删除*!/
// 存储表格中选中的行数据（批量删除用）
const selectedRows = ref([]);

// 选中行变化时触发：更新 selectedRows
const handleSelectionChange = (val) => {
  selectedRows.value = val; // val 是选中的行数据数组
};

const delBatchs = () => {
  // 1. 先判断是否选中数据
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请先选中要删除的供应商");
    return; // 没有选中则终止操作
  }

  // 2. 提取选中行的 id 数组（核心：后端需要的是 ids 数组）
  const selectedIds = selectedRows.value.map(row => row.id);
  console.log("批量删除的 ids：", selectedIds); // 示例：[1,2,3]

  // 调试：查看序列化后的数据
  const testData = {selectedIds};
  const serializedData = qs.stringify(testData, {indices: false});
  console.log("序列化后的数据：", serializedData);

  // 3. 弹确认框，确认后发送批量删除请求
  ElMessageBox.confirm(
      `此操作将永久删除选中的 ${selectedRows.value.length} 个供应商，是否继续？`,
      "批量删除提示",
      {
        confirmButtonText: "确认删除",
        cancelButtonText: "取消",
        type: "error" // 用 error 类型增强警示性
      }
  )
      .then(() => {
        // 4. 调用批量删除接口（传递 ids 数组）

        api.postJson("supplier/del", selectedIds).then(res => {
          if (res.code === 200) {
            ElMessage.success(`批量删除成功，共删除 ${selectedRows.value.length} 条数据`);
            // 5. 重置选中状态 + 重新查询列表
            selectedRows.value = []; // 清空选中行
            queryCondition.value.pageNum = 1; // 重置到第1页
            query(); // 刷新表格数据
          } else {
            ElMessage.error("批量删除失败，联系管理员");
          }
        });
      })
      .catch(() => {
        // 6. 用户取消删除时的提示（可选）
        ElMessage.info("已取消批量删除");
      });
};*/


/*修改供应商*/
const updateSupplierDialogVisible = ref(false)
// 表单数据
const updateSupplierForm = reactive({
  id:"",
  supplierName: '',
  contacts: '',
  contactPhone: '',
  contactEmail: '',
  contactAddress: '',
  bankOfDeposit: '',
  accountNo: ''
});

let updateSupplierFormRef =ref()

const openUpdateDialog = (rowData) => {
  if (updateSupplierFormRef.value) {
    updateSupplierFormRef.value.clearValidate();
  }
  updateSupplierDialogVisible.value = true; // 显示对话框

  // 将表格行数据赋值给修改表单，实现回显
  for (const key in rowData) {
    if (updateSupplierForm.hasOwnProperty(key)) {
      updateSupplierForm[key] = rowData[key];
    }
  }
  console.log("表格行数据 rowData：", rowData);
  console.log("赋值后的 updateSupplierForm：", updateSupplierForm);
};

const submitUpdateForm = () => {
  // 先执行修改表单的校验
  updateSupplierFormRef.value.validate((valid) => {
    if (valid) { // 校验通过才发接口
      api.postJson("supplier/updateSupplier", updateSupplierForm).then(result => {
        if (result.code == 200) {
          ElMessage.success("修改成功");
          // 关闭对话框并重置表单（防止下次打开有数据残留）
          updateSupplierDialogVisible.value = false;
          updateSupplierFormRef.value.resetFields();
          // 重新查询列表，实时更新表格数据
          pageInfo.value.pageNum = 1;
          query();
        } else {
          ElMessage.error("修改失败，联系管理员");
        }
      });
    } else {
      // 校验失败，提示用户修正
      ElMessage.error("表单填写有误，请检查后重试");
      return false;
    }
  });
};

/*新增供应商*/
let addSupplierDialogVisible = ref(false)

// 表单数据
const addSupplierForm = reactive({
  supplierName: '',
  contacts: '',
  contactPhone: '',
  contactEmail: '',
  contactAddress: '',
  bankOfDeposit: '',
  accountNo: ''
});

// 表单引用，用于表单校验
let addSupplierFormRef = ref();


// 表单校验规则
const rules = {
  supplierName: [{ required: true, message: '请输入供应商名称', trigger: 'blur' }],
  contacts: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1\d{10}$/, message: '联系电话必须是11位手机号', trigger: 'blur' }
  ],
  contactEmail: [
    { required: true, message: '请输入联系邮箱', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
      message: '邮箱格式不正确，需包含@和.com等后缀',
      trigger: 'blur'
    }
  ],
  contactAddress: [{ required: true, message: '请输入联系地址', trigger: 'blur' }],
  bankOfDeposit: [{ required: true, message: '请输入开户银行', trigger: 'blur' }],
  accountNo: [{ required: true, message: '请输入开户帐号', trigger: 'blur' }]
};

// 提交新增表单
let submitAddForm = () => {
  // 先执行表单校验
  addSupplierFormRef.value.validate((valid) => {
    if (valid) { // 只有校验通过才发送请求
      api.postJson("supplier/addSupplier", addSupplierForm).then(result => {
        if (result.code == 200) {
          ElMessage.success("新增成功");
          // 关闭对话框，清空表单
          addSupplierDialogVisible.value = false;
          addSupplierFormRef.value.resetFields();
          // 重新查询
          pageInfo.value.pageNum = 1;
          query();
        }
      });
    } else {
      // 校验失败时提示
      ElMessage.error("表单填写有误，请检查后重试");
      return false; // 阻止提交
    }
  });
}

/*查询*/
//下拉框
const selectCondition = ref([{
  name: "供应商名称",
  prop: "suppliername"
}, {
  name: "联系人",
  prop: "contacts"
}, {
  name: "联系电话",
  prop: "phone"
}, {
  name: "地址",
  prop: "address"
}, {
  name: "开户账号",
  prop: "account"
}, {
  name: "开户银行",
  prop: "bank"
}])

// 定义分页信息对象，与后端pageInfo结构对应
let pageInfo = ref({
  pageNum: 1,       // 当前页码
  pageSize: 10,     // 每页条数
  total: 0,         // 总记录数
  list: []          // 当前页的数据列表
});

let queryCondition = ref({
  inputCondition: "",
  queryCondition: "",
  pageNum: "1",
  pageSize: "3"
})
let query = () => {
  //挂载的时候执行这个方
  api.get("supplier/supplier/list", queryCondition.value).then(result => {
    pageInfo.value = result.data
    //console.log(pageInfo.value)
  })
}

const selectValue = ref("");
const changeQueryCondition=(selectedProp)=>{
  queryCondition.value.queryCondition=selectedProp
  //selectCondition.value = [...selectCondition.value];
  console.log(selectedProp)
}

/*const selectable = (row, index) => {
  return true;
};*/

const handleSizeChange = (size) => {
  //pageInfo.value.pageSize=size
  queryCondition.value.pageNum = 1
  queryCondition.value.pageSize = size
  query()
}

const handleCurrentChange = (page) => {
  //pageInfo.value.pageNum=page
  queryCondition.value.pageNum = page
  query()
}

onMounted(() => {
  //挂载的时候执行查询列表
  query()
})

</script>

<style scoped>
/* 全局样式 */
:deep(.el-dialog__header) {
  padding: 16px 20px 10px;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-dialog__title) {
  font-weight: 600;
  color: #303133;
}

/* 操作栏样式 */
.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 16px 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.left-operations {
  display: flex;
  align-items: center;
  gap: 12px;
}

.right-operations {
  display: flex;
  gap: 12px;
}

.query-select, .query-input {
  margin-right: 8px;
}

.query-btn, .action-btn {
  border-radius: 6px;
  font-weight: 500;
}

/* 表格容器 */
.table-container {
  margin-top: 16px;
}

.table-card {
  border-radius: 8px;
  border: none;
}

:deep(.table-card .el-card__header) {
  padding: 16px 20px;
  background: #fafafa;
  border-bottom: 1px solid #e8e8e8;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.card-total {
  font-size: 14px;
  color: #606266;
}

/* 表格样式 */
.data-table {
  border-radius: 6px;
  overflow: hidden;
}

:deep(.data-table .el-table__header) {
  background: #f5f7fa;
}

:deep(.data-table .el-table th) {
  background: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

.table-btn {
  border-radius: 4px;
  margin: 2px;
}

/* 分页样式 */
.pagination-container {
  display: flex;
  justify-content: flex-end;
  padding: 16px 0 8px;
  margin-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.custom-pagination {
  justify-content: flex-end;
}

/* 对话框样式 */
.custom-dialog, .product-dialog {
  border-radius: 8px;
}

.dialog-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 20px;
  padding: 0 0 16px;
  border-bottom: 1px solid #f0f0f0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.dialog-header i {
  color: #409EFF;
  font-size: 18px;
}

.dialog-form {
  padding: 0 8px;
}

.form-row {
  display: flex;
  gap: 20px;
}

.form-row .el-form-item {
  flex: 1;
}

:deep(.dialog-form .el-form-item__label) {
  font-weight: 500;
}

:deep(.dialog-form .el-input__inner) {
  border-radius: 6px;
}

/* 搜索卡片样式 */
.search-card {
  margin-bottom: 16px;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
}

:deep(.search-card .el-card__body) {
  padding: 20px;
}

.search-form {
  padding: 0;
}

.search-row {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 12px;
}

.search-row:last-child {
  margin-bottom: 0;
}

.search-form-item {
  margin-bottom: 0 !important;
}

:deep(.search-form .el-form-item__label) {
  font-weight: 500;
  color: #606266;
  width: 80px;
  text-align: right;
}

.search-btn {
  border-radius: 6px;
  font-weight: 500;
}

/* 商品表格卡片 */
.product-table-card {
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  margin-top: 16px;
}

:deep(.product-table-card .el-card__header) {
  padding: 12px 16px;
  background: #fafafa;
  border-bottom: 1px solid #e8e8e8;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-title {
  font-weight: 600;
  color: #303133;
}

.table-tips {
  font-size: 12px;
  color: #909399;
}

:deep(.product-table-card .el-card__body) {
  padding: 0;
}

.product-table {
  border-radius: 6px;
}

.price-text {
  color: #e6a23c;
  font-weight: 600;
}

.color-tag {
  font-weight: 500;
}

/* 供应商信息区域 */
.supplier-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 16px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-radius: 8px;
  border-left: 4px solid #409EFF;
}

.product-count {
  color: #606266;
  font-size: 14px;
  font-weight: 500;
}

.selected-products-card {
  border: 1px solid #e8e8e8;
  border-radius: 8px;
}

:deep(.selected-products-card .el-card__body) {
  padding: 0;
}

.selected-table {
  border-radius: 6px;
}

/* 底部按钮区域 */
.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.selection-info {
  color: #606266;
  font-size: 14px;
}

.selection-count {
  color: #409EFF;
  font-weight: 600;
  font-size: 16px;
  margin: 0 4px;
}

.footer-buttons {
  display: flex;
  gap: 12px;
}

/* 按钮样式 */
.cancel-btn {
  border-radius: 6px;
  padding: 10px 20px;
}

.confirm-btn {
  border-radius: 6px;
  font-weight: 500;
  padding: 10px 20px;
}

.delete-btn {
  border-radius: 4px;
  font-size: 12px;
}

.action-btn {
  border-radius: 6px;
  font-weight: 500;
}

/* 供应商商品对话框特殊样式 */
.supplier-products-dialog {
  max-width: 90vw;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .operation-bar {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .left-operations {
    flex-wrap: wrap;
  }

  .form-row {
    flex-direction: column;
    gap: 0;
  }

  .search-row {
    flex-direction: column;
    align-items: stretch;
  }

  .search-row .el-form-item {
    width: 100%;
  }

  .dialog-footer {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .footer-buttons {
    justify-content: flex-end;
  }
}

/* 动画效果 */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from, .fade-leave-to {
  opacity: 0;
}

/* 滚动条美化 */
:deep(::-webkit-scrollbar) {
  width: 6px;
  height: 6px;
}

:deep(::-webkit-scrollbar-track) {
  background: #f1f1f1;
  border-radius: 3px;
}

:deep(::-webkit-scrollbar-thumb) {
  background: #c1c1c1;
  border-radius: 3px;
}

:deep(::-webkit-scrollbar-thumb:hover) {
  background: #a8a8a8;
}

/* 加载状态美化 */
:deep(.el-loading-mask) {
  border-radius: 6px;
}

:deep(.el-loading-spinner .el-loading-text) {
  color: #409EFF;
  font-weight: 500;
}
</style>